#include "apue.h"
#include <sys/wait.h>
#include <errno.h>

static void sig_cld(int);

int main() {
    int status;
    //printf("SIGCHLD = %d\n", SIGCHLD);
    //printf("SIGCLD = %d\n", SIGCLD);

    pid_t pid;
    if (signal(SIGCLD, sig_cld) == SIG_ERR)
        perror("signal error");
    if ((pid= fork()) < 0) {
        perror("fork error");
    } else if (pid == 0) {
        sleep(2);
        _exit(2);
    }

    while ((pid= wait(&status)) > 0) {
        printf("child pid %d terminate\n", pid);
        pr_exit(status);
    }
    if (errno != 10) {
        err_sys("wait err");
    } else {
        printf("no child process\n");
    }
    
    exit(0);
}

static void sig_cld(int signo) {    /* interrupts pause() */
    pid_t pid; 
    int status;
    
    printf("SIGCLD received\n");
    //if (signal(SIGCLD, sig_cld) == SIG_ERR)
    //    perror("signal error");
    if ((pid= wait(&status)) < 0)   /* fetch child status */
        perror("wait error");
    printf("pid = %d\n", getpid());
}
